<?php

namespace app\common\cachemodel\ai_chat_room;

use app\common\model\BaseCache;
use XznsTools\cache\CacheManage;

class AiChatUserConfig extends BaseCache
{
    protected $table = 'ai_chat_room.ai_chat_user_config';

    protected $cacheModel = 'ai_chat_room.chat_config';

    /**
     * 保存数据
     * @param array $data
     * @return int
     */
    public function SaveData(array $data)
    {
        try
        {
            if (is_array($data['config']))
            {
                $data['config'] = json_encode($data['config'], JSON_UNESCAPED_UNICODE);
            }
            $id = $this->insertGetId($data);
            return (int)$id;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
    }

    /**
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function UpdateData(int $id, array $data)
    {
        try
        {
            if (isset($data['config']) && is_array($data['config']))
            {
                $data['config'] = json_encode($data['config'], JSON_UNESCAPED_UNICODE);
            }
            $data['update_time'] = time();
            $this->where(['id' => $id])->update($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCacheTime(10)->setCache($data);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        $field = 'c.uid,c.config,c.type,c.sl_id,c.create_time,c.update_time,sl.content as story_line_content';
        try
        {
            $data = $this->alias('c')->join('ai_chat_room.ai_chat_story_line sl', 'c.sl_id=sl.id', 'left')
                ->field($field)
                ->where(['c.id' => ['in', $ids]])
                ->column($field, 'c.id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'uid', 'type', 'sl_id', 'create_time', 'update_time']);

            if (isset($itemData['config']))
            {
                $data[$index]['config'] = $itemData['config'] ? json_decode($itemData['config'], true) : [];
            }
            if (isset($itemData['story_line_content']) && !$itemData['story_line_content'])
            {
                $data[$index]['story_line_content'] = '';
            }
        }

        return $data;
    }

    /**
     * 随机或剧情ID
     * @param array $configData
     * @param int $oldSlId 旧的剧情ID
     * @return int
     */
    public function randStoryLineIds(array $configData, int $oldSlId = 0)
    {
        $aiChatRoomConfig = config('ai_chat_room.story_line_data');

        $key = sprintf('%s_%s_%s', $configData['option10']['ids'][0], $configData['option20']['ids'][0], $configData['sex_type']['ids'][0]);

        if (!isset($aiChatRoomConfig[$key]))
        {
            return 0;
        }
        $slIds = $aiChatRoomConfig[$key];
        $resSlIds = [];
        foreach ($slIds as $slId)
        {
            if ($slId !== $oldSlId)
            {
                $resSlIds[] = $slId;
            }
        }
        $randIndex = array_rand($resSlIds);

        return $resSlIds[$randIndex];
    }
}